
import RouterLink from './RouterLink'
import RouterView from './RouterView'
class LcRouter {
	constructor(options) {
		// 判断是否有传入模式
		this.mode = options.mode || "hash";
		// 传入数组的路由配置列表
		this.routes = options.routes || [];
		// 根据配置创建路由的匹配映射
		this.routesMap = this.createMap(this.routes)
		this.history = {
			current: null
		}
		// 根据模式来初始化路由
		this.init()
	}

	init () {
		if (this.mode == "hash") {
			// 判断hash是否存在
			location.hash || (location.hash = "/")
			window.addEventListener('DOMContentLoaded', () => {
				this.history.current = location.hash.slice(1)
			})
			window.addEventListener('hashchange', () => {
				this.history.current = location.hash.slice(1)
			})
		}
	}

	createMap (routes) {
		return routes.reduce((pre, current) => {
			pre[current.path] = current.component;
			return pre
		}, {})
	}
}


LcRouter.install = function (Vue) {
	// console.log("安装路由插件")
	// 给vue原型链添加$route,$router
	Vue.mixin({
		beforeCreate () {
			if (this.$options && this.$options.router) {
				console.log(this)
				this._root = this;
				this._router = this.$options.router;
				Vue.util.defineReactive(this, "history", this._router.history)
			} else {
				this._root = this.$parent && this.$parent._root;
			}

			Object.defineProperty(this, "$router", {
				get () {
					return this._root._router;
				}
			})

			Object.defineProperty(this, "$route", {
				get () {
					return this._root._router.history.current
				}
			})
		}
	})

	Vue.component('router-link', RouterLink)
	Vue.component('router-view', RouterView)
	// 给vue添加router-link和router-view组件

	// Vue.component('router-link', {
	// 	props: {
	// 		to: String
	// 	},
	// 	render (h) {
	// 		console.log(this)
	// 		let mode = this._self._root._router.mode;
	// 		let to = mode === 'hash' ? "#" + this.to : this.to;
	// 		return h(
	// 			'a',
	// 			{
	// 				attrs: { href: to }
	// 			},
	// 			this.$slots.default
	// 		)
	// 	}
	// })
	// Vue.component("router-view", {
	// 	render (h) {
	// 		let current = this._self._root._router.history.current;
	// 		let routeMap = this._self._root._router.routesMap;
	// 		return h(routeMap[current])
	// 	}
	// })

}

export default LcRouter